const toString = Object.prototype.toString

export default class ModelHelper {
  /**
   * 转换数据为model结构(接口数据转换)
   *
   * @param {object} origin={}
   * @returns {undefined}
   */
  convert (origin = {}, map) {
    if (!map) {
      return
      // throw new Error('Convert Error: Required second param map!')
    }

    Object.entries(map).forEach(([modelKey, apiKey]) => {
      if (this.isType(apiKey, 'Function')) {
        this[modelKey] = apiKey(origin)
      }
      // eslint-disable-next-line no-void
      if (origin[apiKey] !== void 0) {
        const target = this[modelKey]
        if (target instanceof ModelHelper) {
          target.update(origin[apiKey])
          return
        }
        this[modelKey] = origin[apiKey]
      }
    })
  }

  /**
   * 更新model属性值
   *
   * @param {object} props
   * @returns {undefined}
   */
  update (props) {
    Object.entries(props).forEach(([key, val]) => {
      // eslint-disable-next-line no-prototype-builtins
      if (this.hasOwnProperty(key)) {
        this[key] = val
      }
    })
  }

  /**
   * 判断数据类型
   *
   * @param {any} data
   * @param {string} type
   * @returns {Boolean}
   */
  isType (data, type) {
    return toString.call(data) === `[object ${type}]`
  }
}
